<?php
/**
 * Created by PhpStorm.
 * User: zhengkunming
 * Date: 2018/12/26
 * Time: 6:11 PM
 */

require_once 'mysql_config.php';

$openid = isset($_POST['openid']) ? $_POST['openid'] : '';
$week = isset($_POST['week']) ? $_POST['week'] : '';
$score = isset($_POST['score']) ? $_POST['score'] : '';
$shop = isset($_POST['shop']) ? $_POST['shop'] : '';
$score = intval($score);

if ('' === $openid) {
    $data = array(
        'code' => -1,
        'data' => array(),
        'msg' => 'require openid'
    );
    rtJson($data);
    return;
}

if ('' === $week) {
    $data = array(
        'code' => -1,
        'data' => array(),
        'msg' => 'require week'
    );
    rtJson($data);
    return;
}

if ('' === $score) {
    $data = array(
        'code' => -1,
        'data' => array(),
        'msg' => 'require score'
    );
    rtJson($data);
    return;
}

$query = 'SELECT * FROM answer_score WHERE openid = "' . $openid . '" AND week = ' . $week;

$query_res = mysqli_query($link, $query);

if (FALSE === $query_res) {
    $data = array(
        'code' => -4,
        'data' => array(),
        'msg' => 'database err'
    );
    rtJson($data);
    return;
}


$query_num_rows = $query_res->num_rows;


if (0 === $query_num_rows && -1 === $score) {
//    $answer_score = $query_res->fetch_array();
    $data = array(
        'code' => -3,
        'data' => array(),
        'msg' => 'not answer'
    );
    rtJson($data);
    return;
} else if (0 !== $query_num_rows) {
    $answer_score = $query_res->fetch_object();
    $data = array(
        'code' => -2,
        'data' => $answer_score,
        'msg' => 'have answer'
    );
    rtJson($data);
    return;
} else {

    $r_date = getWeekRange($current_date);
    $query =
        'INSERT INTO answer_score (openid, week, score, created, s_date, e_date, shop) 
value ("' . $openid . '",' . $week . ',' . $score . ',"' . $current_date . '","' . $r_date['sdate'] . '","' . $r_date['edate'] . '","'.$shop.'")';
//    $query_users = 'UPDATE users SET score = score + ' . $score . ' WHERE openid = "' . $openid . '"';
    $query_res = mysqli_query($link, $query);
//    $query_users_res = mysqli_query($link, $query_users);
    if (TRUE === $query_res) {
        $data = array(
            'code' => 0,
            'data' => array(),
            'msg' => 'update success'
        );
        rtJson($data);
        return;
    }
}

